package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import Frame.common.AllUserBorrowingInformation;
import Frame.common.FindBookFrame;
import Frame.common.LoginFrame;
import Frame.common.RegisterFrame;
import Frame.common.Tab;
import Frame.dialog.PersonalImformationMaintenance;
import Frame.librarianFrame.BookBorrowFrame;
import Frame.librarianFrame.BookManageFrame;
import Frame.librarianFrame.BorrowingInformationFrame;
import Frame.librarianFrame.LbBackgroundFrame;
import Frame.readerFrame.ReaderBackgroundFrame;
import Frame.systemAdministratorFrame.SystemBackgroundFrame;
import Frame.systemAdministratorFrame.sUserManageFrame;
import service.Consumer;
import service.Librarian;
import service.LoginService;
import service.SystemAdministrator;
import table.BarCodeAndBook;
import table.Book;
import table.BorrowingInformation;
import table.Borrowingquantity;
import table.Login;
import table.User;

public class Controller implements ActionListener, MouseListener {
	private SystemAdministrator systemAdministratorService;// 这里实例化了
	private sUserManageFrame sUserManageFrame;
	private BookManageFrame bookManageFrame;// "图书管理"界面
	private Librarian librarianService;
	private Consumer consumer;
	private LbBackgroundFrame lbBackgroundFrame;// 图书管理员身份 界面
	private ReaderBackgroundFrame readerBackgroundFrame;// 读者身份 界面
	private SystemBackgroundFrame systemBackgroundFrame;// 系统管理员身份 界面
	private BookBorrowFrame bookBorrowFrame;// "图书借阅"界面
	private BorrowingInformationFrame borrowingInformationAllFrame;// 图书管理员 "借阅查询"界面
	private MyTableMouseMotion myTableMouseMotion;
	private FindBookFrame findBookFrame;// 所有用户的（图书管理员除外） 图书查询界面
	private AllUserBorrowingInformation allUserBorrowingInformation;// 所有用户的（图书管理员除外）借阅查询&续借界面
	private LoginFrame loginFrame;// 登录界面
	private RegisterFrame registerFrame;// 注册界面
	private LoginService loginService;
	private TestDate date;
	private PersonalImformationMaintenance dialog;
	private Tab tab;
	private int selRow = -1;// 选中的表格行索引
	private int selRow1 = -1;
	private int bookId = 0;
	private int userId = 0;
	private int bookBarId = 0;// 续借操作用到的图书编码
	private String loginUserName = null;// 使用系统的当前用户的用户名 由登录时赋值

	public Controller() {
		systemAdministratorService = new SystemAdministrator();
		librarianService = new Librarian();
		consumer = new Consumer();
		loginService = new LoginService();
		// new TableBackGround();//设置jtable的外观
		myTableMouseMotion = new MyTableMouseMotion();
		bookManageFrame = new BookManageFrame(this);
		bookBorrowFrame = new BookBorrowFrame(this);
		date = new TestDate();// 用于获取系统当前时间
		borrowingInformationAllFrame = new BorrowingInformationFrame(this);
		findBookFrame = new FindBookFrame(this);
		allUserBorrowingInformation = new AllUserBorrowingInformation(this);
		sUserManageFrame = new sUserManageFrame(this);// 系统管理员 用户管理界面
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String loginName = sUserManageFrame.getTf3().getText();
		String userName = sUserManageFrame.getTf4().getText();
		String phoneNumber = sUserManageFrame.getTf7().getText();
		String loginPassword = sUserManageFrame.getTf5().getText();
		String identity = (String) sUserManageFrame.getComboBox2().getSelectedItem();
		String sex = sUserManageFrame.getRadioText();
		User user = new User();
		user.setIdentity(identity);
		user.setLoginName(loginName);
		user.setLoginPassword(loginPassword);
		user.setUserName(userName);
		user.setUserPhoneNumber(phoneNumber);
		user.setUserSex(sex);
		// 以bookbarCode表中的主键barCodeId作为图书的唯一编号
		int barCodeId = 0;
		// 系统管理员 用户管理 对用户的增删改查
		// 通过账号 姓名 身份查找用户
		if ("findUser".equals(e.getActionCommand())) {
			String loginName1 = sUserManageFrame.getTf1().getText();
			String userName1 = sUserManageFrame.getTf2().getText();
			String identity1 = (String) sUserManageFrame.getComboBox().getSelectedItem();
			if (loginName1 != null && !"".equals(loginName1) && userName1 != null && !"".equals(userName1)
					&& identity1 != null && !"".equals(identity1)) {
				List<User> result = systemAdministratorService.get(loginName1, userName1, identity1);
				clearUserInformation();
				sUserManageFrame.showSearchResult(result);
			} else if (loginName1 != null && !"".equals(loginName1) && identity1 != null && !"".equals(identity1)) {
				List<User> result = systemAdministratorService.get1(loginName1, identity1);
				clearUserInformation();
				sUserManageFrame.showSearchResult(result); 
			} else if (userName1 != null && !"".equals(userName1) && identity1 != null && !"".equals(identity1)) {
				List<User> result = systemAdministratorService.get2(userName1, identity1);
				clearUserInformation();
				sUserManageFrame.showSearchResult(result);
			} else {
				List<User> result = systemAdministratorService.get3(identity1);
				clearUserInformation();
				sUserManageFrame.showSearchResult(result);
			}
		}
		else if("returnFindAllUser".equals(e.getActionCommand())) {
			clearUserInformation();
			sUserManageFrame.showSearchResult(systemAdministratorService.findAll());
		}
		// 添加用户
		else if ("saveUser".equals(e.getActionCommand())) {
			if (loginName != null && userName != null & phoneNumber != null && identity != null && sex != null
					&& loginPassword != null) {
				systemAdministratorService.save(user);
				clearUserInformation();
				JOptionPane.showMessageDialog(sUserManageFrame, "添加成功!");	
				sUserManageFrame.refresh();
			} else {
				JOptionPane.showMessageDialog(sUserManageFrame, "添加失败,请补全信息");
			}
		}
		// 修改用户信息
		else if ("updateUser".equals(e.getActionCommand())) {
			user.setUserId(userId);
			if (userId != 0 && !loginName.equals("")&& !identity.equals("")
					) {
				systemAdministratorService.update(user);
				clearUserInformation();
				JOptionPane.showMessageDialog(sUserManageFrame, "修改成功!");
				sUserManageFrame.refresh(); 								
			} else {
				JOptionPane.showMessageDialog(sUserManageFrame, "修改失败,请补全用户名信息");
			}
		}
		// 删除用户信息
		else if ("deleteUser".equals(e.getActionCommand())) {	
			//该用户不存在图书借阅记录 可删除
			if(librarianService.findNumberOfDate(sUserManageFrame.getTf3().getText())==0) {
				systemAdministratorService.delete(userId);
				loginService.delete(sUserManageFrame.getTf3().getText());//删除登录信息表的记录
				clearUserInformation();
				JOptionPane.showMessageDialog(sUserManageFrame, "删除成功!");	
				sUserManageFrame.refresh();
			}
			else {
				JOptionPane.showMessageDialog(sUserManageFrame, "删除失败，该用户存在借阅记录，需该用户将所有图书归还后方可删除改用户信息", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
		}
		
		// 图书管理员 对图书的增删改查
		// 通过索书号、书名、作者三者之一 查找图书信息
		else if ("findBook".equals(e.getActionCommand())) {
			String callNumber1 = bookManageFrame.getTf1().getText();
			String bookName1 = bookManageFrame.getTf2().getText();
			String bookWriter1 = bookManageFrame.getTf3().getText();
			if (callNumber1 != null && !"".equals(callNumber1) && bookName1 != null && !"".equals(bookName1)
					&& bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get4(callNumber1, bookName1, bookWriter1);
				bookManageFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1) && bookName1 != null && !"".equals(bookName1)) {
				List<Book> result = librarianService.get1(callNumber1, bookName1);
				bookManageFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1) && bookWriter1 != null
					&& !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get3(callNumber1, bookWriter1);
				bookManageFrame.showSearchResult(result);
			} else if (bookName1 != null && !"".equals(bookName1) && bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get2(bookName1, bookWriter1);
				bookManageFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1)) {
				List<Book> result = librarianService.get5(callNumber1);
				bookManageFrame.showSearchResult(result);
			} else if (bookName1 != null && !"".equals(bookName1)) {
				List<Book> result = librarianService.get6(bookName1);
				bookManageFrame.showSearchResult(result);
			} else if (bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get7(bookWriter1);
				bookManageFrame.showSearchResult(result);
			} else {
				JOptionPane.showMessageDialog(bookManageFrame, "请输入查询内容", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
			clear();
		}
		else if("findAllBook".equals(e.getActionCommand())) {
			clear();
			bookManageFrame.showSearchResult(librarianService.find());//查询所有图书
		}
		// 添加图书
		else if ("saveBook".equals(e.getActionCommand())) {
			Book bk = JudgeInputOfBookManagement();
			if (bk != null) {
				int bookNumber = bk.getBookNumber();
				for(int i=0;i<bookNumber;i++) {//多少本就添加多少次
					librarianService.saveBookBarCode(bk.getBookIsbn(),"在馆");
				}
				librarianService.save(bk);
				clear();//清空文本框的内容 和 红字提示
				JOptionPane.showMessageDialog(bookManageFrame, "添加成功!");		
				bookManageFrame.refresh();					
			} else {
				JOptionPane.showMessageDialog(bookManageFrame, "请输入完整的内容", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
		}
		// 修改图书
		else if ("updateBook".equals(e.getActionCommand())) {
			Book bk = JudgeInputOfBookManagement();
			if (bk != null) {
				librarianService.update(bk);
				for(int i=0;i<bk.getBookNumber()-librarianService.findBookNumber(bk.getBookIsbn());i++) {//多少本就添加多少次
					librarianService.saveBookBarCode(bk.getBookIsbn(),"在馆"); 
				}		
				clear();//清空文本框的内容 和 红字提示
				JOptionPane.showMessageDialog(bookManageFrame, "修改成功!");	
				bookManageFrame.refresh();				
			} else {
				JOptionPane.showMessageDialog(bookManageFrame, "修改失败,请补全信息");
			}
		}
		// 删除图书
		else if ("deleteBook".equals(e.getActionCommand())) {
			//该图书全部在馆 可删除
			if(librarianService.findBookStatus(bookManageFrame.getTf4().getText())) {
				librarianService.delete(librarianService.getBookId(bookManageFrame.getTf4().getText()),bookManageFrame.getTf4().getText());
				clear();//清空文本框的内容 和 红字提示
				JOptionPane.showMessageDialog(bookManageFrame, "删除成功!");		
				bookManageFrame.refresh();
			}
			else {
				JOptionPane.showMessageDialog(bookManageFrame, "该图书存在被借出的情况，需读者归还后方可删除图书信息！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			}
			
		}
		// 图书管理员 图书借还界面 的查找用户相关信息以及图书的信息
		else if ("BorrowFindUser".equals(e.getActionCommand())) {
			int userId = 0;
			String str1 = bookBorrowFrame.getTf1().getText().replaceAll("[^\\d]+", "");// 去掉非数字字符
			userId = systemAdministratorService.getUserId(str1);// 通过输入的用户名找id 判断该用户是否存在
			String str = bookBorrowFrame.getTf2().getText().replaceAll("[^\\d]+", "");// 去掉非数字字符
			if (userId != 0) {
				Iterator<User> iter = librarianService.borrowInformation(userId).iterator();
				while (iter.hasNext()) {
					User us = iter.next();
					bookBorrowFrame.getLb4().setText(us.getLoginName());// 用户名
					bookBorrowFrame.getLb6().setText(us.getIdentity());
				}
				// 如果该用户还没有借书记录
				if (librarianService.find(str1).isEmpty()) {
					bookBorrowFrame.getLb8().setText("0"); // 已借数量
					bookBorrowFrame.getLb10().setText("5");// 可借数量
				} else {
					Iterator<Borrowingquantity> i = librarianService.find(str1).iterator();
					while (i.hasNext()) {
						Borrowingquantity bq = i.next();
						bookBorrowFrame.getLb8().setText(String.valueOf(bq.getBorrowedQuantity())); // 已借数量
						bookBorrowFrame.getLb10().setText(String.valueOf(bq.getLoanableQuantity()));// 可借数量
					}
				}
			} else {
				bookBorrowFrame.getLb4().setText("");// 用户名
				bookBorrowFrame.getLb6().setText("");
				bookBorrowFrame.getLb8().setText("");
				bookBorrowFrame.getLb10().setText("");
				JOptionPane.showMessageDialog(bookManageFrame, "您查找的读者不存在！", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
			if (str != null && !"".equals(str)) {
				barCodeId = Integer.parseInt(str);
				List<BarCodeAndBook> BarCodeAndBook = new ArrayList<BarCodeAndBook>();
				BarCodeAndBook = librarianService.getBookByBarCode(barCodeId);// 获取该表的图书信息
				// 查无此书
				if (BarCodeAndBook.isEmpty()) {
					// 如果表格已经生成过
					if (bookBorrowFrame.getBorrowInformationTable() != null) {
						bookBorrowFrame.refresh();
						JOptionPane.showMessageDialog(bookManageFrame, "您查找的图书不存在！", "WARNING",
								JOptionPane.WARNING_MESSAGE);
					} else {
						JOptionPane.showMessageDialog(bookManageFrame, "您查找的图书不存在！", "WARNING",
								JOptionPane.WARNING_MESSAGE);
					}
				} else {
					// 若输入的文字符合条件 将表格添加
					bookBorrowFrame.showSearchResult(BarCodeAndBook);
				}
			}
			// 当图书编号输入框没有内容时
			else {
				bookBorrowFrame.refresh();
				JOptionPane.showMessageDialog(bookManageFrame, "您查找的图书不存在！", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
		}
		// 借书
		else if ("bookBorrow".equals(e.getActionCommand())) {
			BorrowingInformation borrowingInformation = new BorrowingInformation();
			borrowingInformation.setBorrowingDate(date.getNowTime());// 借书时间
			borrowingInformation.setReturnDate(date.getAfterTime(null));// 理应还书时间
			String loginName1 = bookBorrowFrame.getTf1().getText().replaceAll("[^\\d]+", "");
			borrowingInformation.setLoginName(loginName1);
			String str = bookBorrowFrame.getTf2().getText().replaceAll("[^\\d]+", "");// 去掉非数字字符
			int bookBarId = Integer.parseInt(str);// 图书的唯一编号
			borrowingInformation.setBarCodeId(bookBarId);
			int borrowingTime = 0;
			int loanableQuantity = 0;
			System.out.println("该用户的借阅数量表是有信息" + librarianService.findNumberOfDate(loginName1));

			// 判断借阅信息表是否有该用户、图书编号来判断能否借阅
			if (librarianService.isBorrowingInformation(bookBarId)) {
				JOptionPane.showMessageDialog(bookManageFrame, "该书已被借出，无法借阅！", "WARNING", JOptionPane.WARNING_MESSAGE);
			} else {
				// 如果改用户的借阅数量表还没有数据时 先添加数据
				if (librarianService.findNumberOfDate(loginName1) == 0) {// 从借阅数量表中查记录
					Borrowingquantity bq = new Borrowingquantity();
					bq.setLogin_name(loginName1);
					bq.setBorrowedQuantity(0);
					bq.setLoanableQuantity(5);
					librarianService.save(bq);// 先给读者借阅数量添加数据 之后才能修改
					
				}
				borrowingTime = librarianService.findBorrowingTime(loginName1);// 已借数量 查找该用户的借阅信息表的记录
				loanableQuantity = 5 - borrowingTime;
					if (loanableQuantity > 0) { 

						// 修改借阅数量表的信息 “loanableQuantity-1”是可借数量
						librarianService.updateBorrowingQuantity(loginName1, loanableQuantity - 1, borrowingTime + 1);
						librarianService.updateBookStatus("借出", Integer.parseInt(str));// 修改图书表中的图书状态
						// 添加一条图书借阅信息的数据
						librarianService.saveBorrowingInformation(borrowingInformation);
						bookBorrowFrame.getLb8().setText(String.valueOf(borrowingTime + 1));// 更新已借图书
						bookBorrowFrame.getLb10().setText(String.valueOf(loanableQuantity - 1));// 更新可借图书
						bookBorrowFrame.refresh();
						bookBorrowFrame.getTf2().setText("");
						JOptionPane.showMessageDialog(bookBorrowFrame, "借出成功!");
					} else {
						JOptionPane.showMessageDialog(bookManageFrame, "该用户已达借阅上限，无法进行借阅！", "WARNING",
								JOptionPane.WARNING_MESSAGE);
					}
				

			}

		}
		// 还书 1、删除图书借阅信息中的数据 2、将图书当中的图书状态修改 3、Borrowingquantity表中用户的数据修改
		else if ("bookReturn".equals(e.getActionCommand())) {
			String loginName1 = bookBorrowFrame.getTf1().getText().replaceAll("[^\\d]+", "");// 去掉非数字字符
			String str = bookBorrowFrame.getTf2().getText().replaceAll("[^\\d]+", "");// 图书的唯一编号
			//判断找到的书是否是该用户所借
			if(loginName1.equals(librarianService.getUserName(Integer.parseInt(str)))) {
				librarianService.updateBookStatus("在馆", Integer.parseInt(str));// 修改图书表中的图书状态
				// 修改用户的借阅数量
				int borrowingTime = librarianService.findBorrowingTime(loginName1);// 已借数量
				int loanableQuantity = 5 - borrowingTime;
				librarianService.updateBorrowingQuantity(loginName1, loanableQuantity + 1, borrowingTime - 1);
				bookBorrowFrame.getLb8().setText(String.valueOf(borrowingTime - 1));// 更新已借图书
				bookBorrowFrame.getLb10().setText(String.valueOf(loanableQuantity + 1));// 更新可借图书
				bookBorrowFrame.refresh();
				bookBorrowFrame.getTf2().setText("");
				librarianService.deleteBookBorrowingInformation(Integer.parseInt(str));// 删除图书借阅信息中的数据
				JOptionPane.showMessageDialog(bookBorrowFrame, "还书成功!");
			}
			else {
				JOptionPane.showMessageDialog(bookBorrowFrame, "该书不是"+loginName1+"所借，请输入正确的用户名进行还书操作！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			}
		}
		// 图书管理员 查询读者借阅信息
		else if ("BorrowingInformationFindByLoginName".equals(e.getActionCommand())) {
			if (librarianService.borrowQuery(borrowingInformationAllFrame.getTf1().getText()).isEmpty()) {
				borrowingInformationAllFrame.showSearchResult(
						librarianService.borrowQuery(borrowingInformationAllFrame.getTf1().getText()));
				JOptionPane.showMessageDialog(borrowingInformationAllFrame, "该用户不存在借阅记录，请输入正确的用户名！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			} else
				borrowingInformationAllFrame.showSearchResult(
						librarianService.borrowQuery(borrowingInformationAllFrame.getTf1().getText()));
		}
		// 图书管理员 续借
		else if ("renew".equals(e.getActionCommand())) {
			Iterator<BorrowingInformation> iter = librarianService.getBorrowingInformation(bookBarId).iterator();
			Date borrowDate = null;
			Date returnDate = null;
			Calendar calendar = Calendar.getInstance();
			while (iter.hasNext()) {
				BorrowingInformation us = iter.next();
				borrowDate = us.getBorrowingDate();
				returnDate = us.getReturnDate();
			}
			calendar.setTime(borrowDate);
			int b = calendar.get(Calendar.MONTH);
			System.out.println(b);
			calendar.setTime(returnDate);
			calendar.add(Calendar.MONTH, -5);// 这里就是月份的相减
			int r = calendar.get(Calendar.MONTH);
			System.out.println(r);
			if (r == b) {
				JOptionPane.showMessageDialog(borrowingInformationAllFrame, "该用户借续该书次数已达2次，无法进行续借！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			} else {
				librarianService.renew(bookBarId, date.getAfterTime(returnDate));// 获取当前的应还书时间 传进去+上一个月
				borrowingInformationAllFrame.showSearchResult(
						librarianService.borrowQuery(borrowingInformationAllFrame.getTf1().getText()));
				JOptionPane.showMessageDialog(borrowingInformationAllFrame, "续借成功!");
			}

		}
		// 读者 图书查询 个人信息管理 借阅查询 续借
		// 通过索书号、书名、作者三者之一 查找图书信息
		else if ("findBookByUser".equals(e.getActionCommand())) {
			String callNumber1 = findBookFrame.getTf1().getText();
			String bookName1 = findBookFrame.getTf2().getText();
			String bookWriter1 = findBookFrame.getTf3().getText();
			if (callNumber1 != null && !"".equals(callNumber1) && bookName1 != null && !"".equals(bookName1)
					&& bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get4(callNumber1, bookName1, bookWriter1);
				findBookFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1) && bookName1 != null && !"".equals(bookName1)) {
				List<Book> result = librarianService.get1(callNumber1, bookName1);
				findBookFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1) && bookWriter1 != null
					&& !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get3(callNumber1, bookWriter1);
				findBookFrame.showSearchResult(result);
			} else if (bookName1 != null && !"".equals(bookName1) && bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get2(bookName1, bookWriter1);
				findBookFrame.showSearchResult(result);
			} else if (callNumber1 != null && !"".equals(callNumber1)) {
				List<Book> result = librarianService.get5(callNumber1);
				findBookFrame.showSearchResult(result);
			} else if (bookName1 != null && !"".equals(bookName1)) {
				List<Book> result = librarianService.get6(bookName1);
				findBookFrame.showSearchResult(result);
			} else if (bookWriter1 != null && !"".equals(bookWriter1)) {
				List<Book> result = librarianService.get7(bookWriter1);
				findBookFrame.showSearchResult(result);
			} else {
				JOptionPane.showMessageDialog(findBookFrame, "请输入查询内容", "WARNING", JOptionPane.WARNING_MESSAGE);
			}
		}
		// 读者和图书管理员 修改部分个人信息
		else if ("updateUserByOneself".equals(e.getActionCommand())) {
			User newUser = new User();
			newUser.setUserId(0);
			newUser.setIdentity("读者");
			newUser.setLoginPassword(dialog.getTf1().getText());
			newUser.setUserPhoneNumber(dialog.getTf3().getText());
			newUser.setUserName(dialog.getTf4().getText());
			newUser.setUserSex(dialog.getRadioText());
			newUser.setLoginName(loginUserName);
			consumer.updateByOneself(newUser);
			JOptionPane.showMessageDialog(dialog, "修改成功!");
		}
		// 登录
		else if ("login".equals(e.getActionCommand())) {
			String lUserName = loginFrame.getTf1().getText();
			loginUserName = lUserName;// 将登录者的用户名赋值给属性(loginUserName)
			String password = new String(loginFrame.getTf2().getPassword());
			// 未输入学号/教职工号
			if (lUserName.equals("学号/教职工号") || lUserName.equals("")) {
				loginFrame.getLb2().setVisible(true);
			} else {
				loginFrame.getLb2().setVisible(false);
			}
			// 未输入密码
			if (password.equals("密码") || password.equals("")) {
				loginFrame.getLb3().setVisible(true);
			} else {
				loginFrame.getLb3().setVisible(false);
			}
			if (loginService.check(lUserName).equals(password)) {
				// 这里注意 不同的身份 用不同的对象add(tab)
				// 判断身份
				String loginidentity = loginService.findIdentity(lUserName);
				if (loginService.findIdentity(lUserName).equals(null)) {
					loginFrame.getLb3().setVisible(true);
				} else if (loginidentity.equals("系统管理员")) {
					new SystemBackgroundFrame(this);// 系统管理员
					tab = new Tab();
					systemBackgroundFrame.add(tab);
					systemBackgroundFrame.getLabel9().setText(loginUserName);
				} else if (loginidentity.equals("图书管理员")) {
					new LbBackgroundFrame(this);// 图书管理员
					tab = new Tab();
					lbBackgroundFrame.add(tab);
					lbBackgroundFrame.getLabel9().setText(loginUserName);
				} else if (loginidentity.equals("读者")) {
					new ReaderBackgroundFrame(this);// 读者
					tab = new Tab();
					readerBackgroundFrame.add(tab);
					readerBackgroundFrame.getLabel9().setText(loginUserName);
				}

			}
			// 密码错误
			if (!loginService.check(lUserName).equals(password)) {
				loginFrame.getLb3().setVisible(true);
			}
		}
		// 注册
		else if ("register".equals(e.getActionCommand())) {
			String RuserName = registerFrame.getTf1().getText();
			String Rpassword = new String(registerFrame.getTf2().getPassword());
			// 未输入学号/教职工号
			if (RuserName.equals("学号/教职工号") || RuserName.equals("")) {
				registerFrame.getLb3().setVisible(true);
			} else {
				registerFrame.getLb3().setVisible(false);
			}
			// 未输入密码
			if (Rpassword.equals("密码") || Rpassword.equals("")) {
				registerFrame.getLb4().setVisible(true);
			} else {
				registerFrame.getLb4().setVisible(false);
			}
			if (registerFrame.getCb1().isSelected()) {
				if (!RuserName.equals("学号/教职工号") && !RuserName.equals("") && !Rpassword.equals("密码")
						&& !Rpassword.equals("")) {
					loginService.register(RuserName, Rpassword);
					JOptionPane.showMessageDialog(registerFrame, "注册成功!");
				}

			} else {
				JOptionPane.showMessageDialog(registerFrame, "请勾选“我已阅读并同意相关服务条款和隐私政策”！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			}
		}
		// 读者 续借
		else if ("renewByUser".equals(e.getActionCommand())) {
			Iterator<BorrowingInformation> iter = librarianService.getBorrowingInformation(bookBarId).iterator();
			Date borrowDate = null;
			Date returnDate = null;
			Calendar calendar = Calendar.getInstance();
			while (iter.hasNext()) {
				BorrowingInformation us = iter.next();
				borrowDate = us.getBorrowingDate();
				returnDate = us.getReturnDate();
			}
			calendar.setTime(borrowDate);
			int b = calendar.get(Calendar.MONTH);
			calendar.setTime(returnDate);
			calendar.add(Calendar.MONTH, -5);// 这里就是月份的相减
			int r = calendar.get(Calendar.MONTH);
			System.out.println(r);
			if (r == b) {
				JOptionPane.showMessageDialog(allUserBorrowingInformation, "您续借该书次数已达2次，无法进行续借！", "WARNING",
						JOptionPane.WARNING_MESSAGE);
			} else {
				librarianService.renew(bookBarId, date.getAfterTime(returnDate));// 获取当前的应还书时间 传进去+上一个月
				allUserBorrowingInformation.showSearchResult(librarianService.borrowQuery(loginUserName));
				JOptionPane.showMessageDialog(allUserBorrowingInformation, "续借成功!");
			}
		}
	}

	/**
	 *
	 * 点击表中的行 将对应的信息设置到文本框中
	 */
	@Override
	public void mouseClicked(final MouseEvent e) {
		// 系统管理员
		// 系统管理员 用户管理 选中行拿到用户的信息
		if ("getTableMessage".equals(e.getComponent().getName())) {
			selRow = sUserManageFrame.getUserTable().getSelectedRow(); // 得到选中的行
			userId = systemAdministratorService
					.getUserId(sUserManageFrame.getUserTable().getValueAt(selRow, 0).toString().trim());
			sUserManageFrame.getTf3().setText(sUserManageFrame.getUserTable().getValueAt(selRow, 0).toString().trim());
			sUserManageFrame.getTf4().setText(sUserManageFrame.getUserTable().getValueAt(selRow, 1).toString().trim());
			sUserManageFrame.getComboBox2()
					.setSelectedItem(sUserManageFrame.getUserTable().getValueAt(selRow, 2).toString().trim());
			sUserManageFrame.getTf7().setText(sUserManageFrame.getUserTable().getValueAt(selRow, 4).toString().trim());// 电话
			sUserManageFrame.getTf5().setText(sUserManageFrame.getUserTable().getValueAt(selRow, 3).toString().trim());// 密码
			sUserManageFrame.JudgeJRadioButton(sUserManageFrame.getUserTable().getValueAt(selRow, 5).toString().trim());// 性别
		} else if ("userManage".equals(e.getComponent().getName())) {
			tab.addTTab("用户管理", sUserManageFrame.getContentPane1());
		}
		// 图书管理员
		// 个人信息维护 还没写完 之后要根据登录系统的角色 获取相应的信息
		// 图书信息维护
		else if ("bookImformation".equals(e.getComponent().getName())) {
			tab.addTTab("图书管理", bookManageFrame.getJpanel());
		}
		// 所有人的个人信息维护（系统管理员除外）
		else if ("personalImformation".equals(e.getComponent().getName())) {
			dialog = new PersonalImformationMaintenance(this);
			Iterator<User> iter = consumer.get5(loginUserName).iterator();// 通过用户名找到用户
			while (iter.hasNext()) {
				User user = iter.next();
				dialog.getLb2().setText(user.getLoginName());
				dialog.getLb4().setText(user.getIdentity());
				dialog.getTf1().setText(user.getLoginPassword());
				dialog.getTf3().setText(user.getUserPhoneNumber());
				dialog.getTf4().setText(user.getUserName());
				dialog.JudgeJRadioButton(user.getUserSex());
			}
		} else if ("getBookMessage".equals(e.getComponent().getName())) {
			selRow1 = bookManageFrame.getBookTable().getSelectedRow(); // 得到选中的行
			bookManageFrame.getLb12().setVisible(false);
			bookManageFrame.getLb13().setVisible(false);
			bookManageFrame.getTf6().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 0).toString().trim());
			bookManageFrame.getTf7().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 1).toString().trim());
			bookManageFrame.getTf10().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 5).toString().trim());
			bookManageFrame.getTf5().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 3).toString().trim());
			bookManageFrame.getTf8().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 4).toString().trim());
			bookManageFrame.getTf9().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 2).toString().trim());
			// bookManageFrame.getComboBox().setSelectedItem(bookManageFrame.getBookTable().getValueAt(selRow1,
			// 6).toString().trim());
			bookManageFrame.getTf4().setText(bookManageFrame.getBookTable().getValueAt(selRow1, 6).toString().trim());
		}
		// 图书借还界面
		else if ("bookBorrow".equals(e.getComponent().getName())) {
			tab.addTTab("图书借还", bookBorrowFrame.getContentPane());
		}

		// 借阅查询界面
		else if ("borrowQuery".equals(e.getComponent().getName())) {
			tab.addTTab("借阅借阅查询 & 续借", borrowingInformationAllFrame.getContentPane());
		}
		// 图书管理员 获取需要续借的行的信息
		else if ("getRenewBook".equals(e.getComponent().getName())) {
			selRow1 = borrowingInformationAllFrame.getBorrowInformationAll().getSelectedRow(); // 得到选中的行
			bookBarId = Integer.parseInt(
					borrowingInformationAllFrame.getBorrowInformationAll().getValueAt(selRow1, 3).toString().trim());
		}
		// 除了图书管理员外 其他用户查询图书的界面
		else if ("bookFind".equals(e.getComponent().getName())) {
			tab.addTTab("图书查询", findBookFrame.getJpanel());
		}
		// 除了图书管理员外 其他用户查询自身图书借阅信息的界面
		else if ("borrowQueryByUser".equals(e.getComponent().getName())) {
			tab.addTTab("借阅查询 & 续借", allUserBorrowingInformation.getContentPane());
			allUserBorrowingInformation.showSearchResult(librarianService.borrowQuery(loginUserName));
		}
		// 注册新账户
		else if ("newAccount".equals(e.getComponent().getName())) {
			registerFrame = new RegisterFrame(this);
		} else if ("getRenewBookByUser".equals(e.getComponent().getName())) {
			selRow1 = allUserBorrowingInformation.getBorrowInformationAll().getSelectedRow(); // 得到选中的行
			bookBarId = Integer.parseInt(
					allUserBorrowingInformation.getBorrowInformationAll().getValueAt(selRow1, 3).toString().trim());
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public Book JudgeInputOfBookManagement() {
		// 作者 出版社 索书号 数量 价格 状态 编号
		String bookWriter = bookManageFrame.getTf7().getText();
		String bookName = bookManageFrame.getTf6().getText();
		String bookPublishingHouse = bookManageFrame.getTf9().getText();
		String bookCallNumber = bookManageFrame.getTf5().getText();
		String bookIsbn = bookManageFrame.getTf4().getText();
		int bookNumber = 0;
		double bookPrice = 0;
		Book bk = new Book();
		bk.setBookCallNumber(bookCallNumber);
		bk.setBookWriter(bookWriter);
		bk.setBookIsbn(bookIsbn); 
		bk.setBookName(bookName);
		bk.setBookPublishingHouse(bookPublishingHouse); 
		bk.setBookId(librarianService.getBookId(bookIsbn));// 这里随便设了个值进去
		// 去掉非数字字符
		if (bookManageFrame.getTf8().getText().replaceAll("[^\\d]+", "")!= null && !"".equals(bookManageFrame.getTf8().getText().replaceAll("[^\\d]+", ""))) { // 这里一定要写两个判断，否则无法执行判断语句
			bookNumber = Integer.parseInt(bookManageFrame.getTf8().getText());
		} else {
			bookManageFrame.getLb12().setVisible(true);
		}
		if (bookManageFrame.getTf10().getText().replaceAll("[^\\d]+", "") != null && !"".equals(bookManageFrame.getTf10().getText().replaceAll("[^\\d]+", ""))) {
			bookPrice = Double.parseDouble(bookManageFrame.getTf10().getText());
		} else {
			bookManageFrame.getLb13().setVisible(true);
		} 
		bk.setBookNumber(bookNumber);
		bk.setBookPrice(bookPrice);
		if (!"".equals(bookWriter)  && !"".equals(bookName)&& !"".equals(bookPublishingHouse)  && !"".equals(bookCallNumber) 
				&& bookNumber!=0 && bookPrice!=0 && !"".equals(bookIsbn) ) {
			System.out.println(bk.toString());
			return bk;
		}
		return null;
	}

	public void clear() {
		bookManageFrame.getTf4().setText("");
		bookManageFrame.getTf5().setText("");
		bookManageFrame.getTf6().setText("");
		bookManageFrame.getTf7().setText("");
		bookManageFrame.getTf8().setText("");
		bookManageFrame.getTf9().setText("");
		bookManageFrame.getTf10().setText("");
		bookManageFrame.getLb12().setVisible(false);
		bookManageFrame.getLb13().setVisible(false);
		
	}
public void clearUserInformation() {
	sUserManageFrame.getTf3().setText("");
	sUserManageFrame.getTf4().setText("");
	sUserManageFrame.getTf7().setText("");
	sUserManageFrame.getTf5().setText("");
	sUserManageFrame.getComboBox2().setSelectedItem("");
	sUserManageFrame.getBt4().setFocusable(false);;
	sUserManageFrame.getBt5().setFocusable(false);
}
	public SystemAdministrator getSystemAdministratorService() {
		return systemAdministratorService;
	}

	public void setSystemAdministratorService(SystemAdministrator systemAdministratorService) {
		this.systemAdministratorService = systemAdministratorService;
	}

	public void setsUserManageFrame(sUserManageFrame sUserManageFrame) {
		this.sUserManageFrame = sUserManageFrame;
	}

	public Librarian getLibrarianService() {
		return librarianService;
	}

	public void setLibrarianService(Librarian librarianService) {
		this.librarianService = librarianService;
	}

	public void setLbBackgroundFrame(LbBackgroundFrame lbBackgroundFrame) {
		this.lbBackgroundFrame = lbBackgroundFrame;
	}

	public BookManageFrame getBookManageFrame() {
		return bookManageFrame;
	}

	public void setBookManageFrame(BookManageFrame bookManageFrame) {
		this.bookManageFrame = bookManageFrame;
	}

	public BookBorrowFrame getBookBorrowFrame() {
		return bookBorrowFrame;
	}

	public void setBookBorrowFrame(BookBorrowFrame bookBorrowFrame) {
		this.bookBorrowFrame = bookBorrowFrame;
	}

	public MyTableMouseMotion getMyTableMouseMotion() {
		return myTableMouseMotion;
	}

	public ReaderBackgroundFrame getReaderBackgroundFrame() {
		return readerBackgroundFrame;
	}

	public void setReaderBackgroundFrame(ReaderBackgroundFrame readerBackgroundFrame) {
		this.readerBackgroundFrame = readerBackgroundFrame;
	}

	public SystemBackgroundFrame getSystemBackgroundFrame() {
		return systemBackgroundFrame;
	}

	public void setSystemBackgroundFrame(SystemBackgroundFrame systemBackgroundFrame) {
		this.systemBackgroundFrame = systemBackgroundFrame;
	}

	public void setLoginFrame(LoginFrame loginFrame) {
		this.loginFrame = loginFrame;
	}

	public PersonalImformationMaintenance getDialog() {
		return dialog;
	}

	public void setDialog(PersonalImformationMaintenance dialog) {
		this.dialog = dialog;
	}

}
